package com.qingke.oms.command.shop;

import java.util.List;
import java.util.Set;

import com.qingke.oms.command.ShopCommand;
import com.qingke.oms.pojo.Shop;
import com.qingke.oms.pojo.ShoppingCart;
import com.qingke.oms.pojo.ShoppingCartItem;
import com.qingke.oms.pojo.User;
import com.qingke.oms.util.OMSConsole;

public class PlaceOrderCommand extends ShopCommand {

	public PlaceOrderCommand(User user, Shop shop) {
		super(user, shop);
	}

	@Override
	public void execute() {
		ShoppingCart shoppingCart=null;
		user=dao.selectNewestUserById(user.getId());
		Set<ShoppingCart> shoppingCarts=user.getShoppingCarts();
		for(ShoppingCart sc:shoppingCarts){
			if(sc.getShop().getId()==shop.getId()){
				shoppingCart=sc;
				break;
			}
		}
		if(shoppingCart==null){
			OMSConsole.println("you have never add goods to shopping cart.");
			OMSConsole.println("so please add goods to shopping cart first.");
			return ;
		}
		List<ShoppingCartItem> items=dao.selectShoppingCartItemByShoppingCart(shoppingCart);
		if(items.size()==0){
			OMSConsole.println("your shopping cart is empty.");
			return ;
		}
		boolean isAllZero=true;
		for(ShoppingCartItem item:items){
			if(item.getQuantity()!=0){
				isAllZero=false;
				break;
			}
		}
		if(isAllZero){
			OMSConsole.println("your shopping cart is empty.");
			return ;
		}
		
		String cmd;
		OMSConsole.println("are you sure place order?");
		while(true){
			cmd=OMSConsole.promptNotEmpty("sure>").trim();
			if("yes".equalsIgnoreCase(cmd)){
				break;
			}
			else if("no".equalsIgnoreCase(cmd)){
				OMSConsole.println("cancel place order success.");
				return ;
			}
			else if("help".equalsIgnoreCase(cmd)){
				OMSConsole.println("- yes    sure to place order");
				OMSConsole.println("- no     cancel to place order");
			}
			else{
				OMSConsole.println("err input");
			}
		}
		
		boolean isSuccess=dao.createOrder(shoppingCart);
		if(!isSuccess){
			OMSConsole.println("create order failed.");
			return ;
		}
		OMSConsole.println("place order success.");
	}

}
